package com.dldata.devtools30.utils.word;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.utils.StringUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.util.*;

public class WordUtil {

    private final static Logger logger = LoggerFactory.getLogger(WordUtil.class);


    public static List<Map> getTableData(String filePath) {
        List<Map> fieldDataList=new LinkedList<>();
        try {
            FileInputStream in = new FileInputStream(filePath);
            if (filePath.toLowerCase().endsWith("docx")) {
                XWPFDocument xwpf = new XWPFDocument(in);
//               得到段落信息
//		    	 List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();
//                得到word中的表格

                Iterator<XWPFTable> it = xwpf.getTablesIterator();
                while (it.hasNext()) {
                    XWPFTable table =  xwpf.getTableArray(0);
                    List<XWPFTableRow> rows = table.getRows();
                    for (int i = 0; i < rows.size(); i++) {
                        XWPFTableRow row = rows.get(i);
                        List<XWPFTableCell> cells = row.getTableCells();
                        Map map=new HashMap();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            map.put(j,cell.getText());
                        }
                        fieldDataList.add(map);
                    }

                }
            } else {
                //如果是office2003 doc格式
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator it = new TableIterator(range);
                //迭代文档中的表格
                if (it.hasNext()) {
                    Table tb = (Table) it.next();
                    //迭代行，默认从0开始
                    for (int i = 0; i < tb.numRows(); i++) {
                        TableRow tr = tb.getRow(i);
                        //迭代列，默认从0开始

                        Map map=new HashMap();
                        for (int j = 0; j < tr.numCells(); j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            //取得单元格的内容
                            StringBuilder stringBuilder=new StringBuilder();
                            for (int k = 0; k < td.numParagraphs(); k++) {
                                Paragraph para = td.getParagraph(k);
                                String str = para.text();
                                //去除后面的特殊符号
                                if (null != str && !"".equals(str)) {
                                    str = str.substring(0, str.length() - 1);
                                }
                                stringBuilder.append(str);
                            }
                            if(stringBuilder.toString().equalsIgnoreCase("RYSJS")){
                                System.out.println();
                            }
                            map.put(j,stringBuilder.toString());
                        }
                        fieldDataList.add(map);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return fieldDataList;

    }

    public static void main(String[] args) {
        List<Map> mapList=
        WordUtil.getTableData("F:\\projects\\zkptplantform\\document\\otherdocument\\病案首页及接口规范\\接口规范\\云南省（国家标准）\\卫统4-1表接口规范1.doc");
        List<FieldData> fieldDataListYn=new LinkedList<>();
        for (int i = 1; i < mapList.size(); i++) {
            Map map = mapList.get(i);
            FieldData fieldData=new FieldData();
            fieldData.fieldName=map.get(0).toString().trim().trim();
            fieldData.fieldType=map.get(1).toString().trim();
            fieldData.canBeNull=map.get(2).toString().trim();
            fieldData.fieldNameZh=map.get(3).toString().trim();
            fieldData.xh=Integer.valueOf(map.get(4).toString().trim());
            String length=
                    fieldData.fieldType.substring(fieldData.fieldType.indexOf('(')+1);
            length=length.substring(0,length.length()-1);
            if(length.indexOf(',')==-1){
                fieldData.fieldLength=Integer.valueOf(length);
                fieldData.fieldPreLength=0;
            }else{
                fieldData.fieldLength=Integer.valueOf(length.split(",")[0].trim());
                fieldData.fieldPreLength=Integer.valueOf(length.split(",")[1].trim());;
            }
            fieldDataListYn.add(fieldData);
        }

        mapList=
                WordUtil.getTableData("F:\\projects\\zkptplantform\\document\\otherdocument\\病案首页及接口规范\\接口规范\\河北省（国家标准）\\河北接口规范2016.doc");
        List<FieldData> fieldDataListHn=new LinkedList<>();
        for (int i = 1; i < mapList.size(); i++) {
            Map map = mapList.get(i);
            FieldData fieldData=new FieldData();
            fieldData.fieldName=map.get(0).toString().trim();
            fieldData.fieldType=map.get(1).toString().trim();
            fieldData.canBeNull=map.get(2).toString().trim();
            fieldData.fieldNameZh=map.get(3).toString().trim();
            if(StringUtil.isEmptyOrLength0(map.get(4))){
                System.out.println(fieldData);
                System.out.println(JSON.toJSONString(map));
            }
            String length=
            fieldData.fieldType.substring(fieldData.fieldType.indexOf('(')+1);
            length=length.substring(0,length.length()-1);
            if(length.indexOf(',')==-1){
                fieldData.fieldLength=Integer.valueOf(length);
                fieldData.fieldPreLength=0;
            }else{
                fieldData.fieldLength=Integer.valueOf(length.split(",")[0].trim());
                fieldData.fieldPreLength=Integer.valueOf(length.split(",")[1].trim());;
            }
            fieldData.xh=Integer.valueOf(map.get(4).toString().trim());
            fieldDataListHn.add(fieldData);
        }

        for (int i = 1; i < fieldDataListHn.size(); i++) {
            FieldData fieldData = fieldDataListHn.get(i);
            FieldData fieldDataYn=
            fieldDataListYn.get(i);
            if(!fieldData.equals(fieldDataYn)){
                System.out.println(fieldData.toString().trim()+"::"+fieldDataYn.toString().trim());
            }
        }

    }

    public static class FieldData{
       public String fieldName="";
       public String fieldType="";
       public Integer fieldLength=0;
       public Integer fieldPreLength=0;
       public  String canBeNull="";
       public  String fieldNameZh="";
       public  Integer xh=0;

        @Override
        public String toString() {
            return "FieldData{" +
                    "fieldName='" + fieldName + '\'' +
                    ", fieldType='" + fieldType + '\'' +
                    ", fieldLength=" + fieldLength +
                    ", fieldPreLength=" + fieldPreLength +
                    ", canBeNull='" + canBeNull + '\'' +
                    ", fieldNameZh='" + fieldNameZh + '\'' +
                    ", xh=" + xh +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            FieldData fieldData = (FieldData) o;
            return Objects.equals(fieldName, fieldData.fieldName) &&
                    Objects.equals(fieldType, fieldData.fieldType) &&
                    Objects.equals(canBeNull, fieldData.canBeNull) &&
                    Objects.equals(fieldNameZh, fieldData.fieldNameZh) &&
                    Objects.equals(xh, fieldData.xh);
        }

        @Override
        public int hashCode() {
            return Objects.hash(fieldName, fieldType, canBeNull, fieldNameZh, xh);
        }
    }
}
